package com.RLFZ.utils;

import com.RLFZ.configEntity.AliYunProperties;
import com.RLFZ.vo.DataView;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Slf4j
public class AliYunFileUtil {
    // 设置最大文件大小为5MB
    private static final long AVATAR_MAX_SIZE = 1024 * 500;

    @Autowired
    private AliYunProperties aliYunProperties;

    @Autowired
    private OSS ossClient;

    public DataView uploadFile(@RequestParam("file") MultipartFile file,
                               HttpServletRequest request, HttpSession session) throws IOException {
        log.warn("/file/uploadFile - {}", file);
        DataView dataView = new DataView();
        //空文件验证
        if (file.isEmpty()) {
            dataView.setMsg("上传文件异常！文件不能为空！");
        }
        //文件大小
        long fileSize = file.getSize();
        if (fileSize > AVATAR_MAX_SIZE) {
            dataView.setMsg("文件上传异常！文件大小超过上限：" + (AVATAR_MAX_SIZE / 1024) + "kb");
        }

        //生成文件名 --> 直接使用uuid+文件后缀
        String oFilename = file.getOriginalFilename();
        Integer index = oFilename.lastIndexOf(".");
        String suffix = "";
        if (index != -1) {
            suffix = oFilename.substring(index);
        }
        String filename = UUID.randomUUID().toString() + suffix;

        byte[] bytes = file.getBytes();


        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tGyD4nvevVk9aoz5WP5";
        String accessKeySecret = "1nbrhnGWBuJeJNJsx2PPYV0Jq6hqQi";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "zbrnb";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "2023/3/23/" + filename;
        // 创建OSSClient实例。
        Date expirationDate = new Date(System.currentTimeMillis() + 1 * 60 * 1000);
        ossClient.generatePresignedUrl(endpoint, accessKeyId, expirationDate);


        try {
            // 填写字符串。
            String content = "Hello OSS，你好世界";
            // 创建PutObjectRequest对象。
            PutObjectResult result = ossClient.putObject(bucketName,
                    objectName, new ByteArrayInputStream(bytes));
            // 如果上传成功，则返回200。
            System.out.println(result.getResponse().getStatusCode());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return dataView;
    }
}
